package com.xszx.server.service;

import com.xszx.server.dto.Page;
import com.xszx.server.entity.Member;
import com.xszx.server.entity.User;
import com.xszx.server.exception.BusinessException;
import com.xszx.server.exception.BusinessExceptionCode;
import com.xszx.server.mapper.MemberMapper;
import com.xszx.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.Date;

@Service
public class MemberService {
    @Resource
    private MemberMapper memberMapper;

    /**
     * 获取分页列表
     * @param page
     * @return
     */
    public Page getAllMembers(Page page){
        int pageNum = page.getPage();
        page.setPage((page.getPage()-1)*page.getSize());
        page.setList(memberMapper.findAll(page));
        page.setTotal(memberMapper.findCount());
        page.setPage(pageNum);
        return page;
    }

    /**
     * 新增或者删除信息
     * @param member
     * @return
     */
    public int saveOrUpdate(Member member){
        if(StringUtils.isEmpty(member.getId())){
            member.setId(UuidUtil.getShortUuid());
            member.setRegisterTime(new Date());//注册时间
            return memberMapper.insert(member);
        }else{
            return memberMapper.updateByPrimaryKey(member);
        }
    }

    /**
     * 物理删除会员
     * @param id
     * @return
     */
    public int del(String id){
        return memberMapper.deleteByPrimaryKey(id);
    }
     /**
     * 获取单个会员
     * @return
     */
    public Member getMember(String id){
        return memberMapper.selectByPrimaryKey(id);
    }

    /**
     * 登录
     */
    public Member login(Member member){
        //进行二次加密
        member.setPassword(DigestUtils.md5DigestAsHex(member.getPassword().getBytes()));
        //查询数据库中会员数据
        Member memberDb = this.getMemberByMobile(member.getMobile());
        if(memberDb == null){//不能登录
            throw  new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }else{
            //判断密码是否相等
            if(memberDb.getPassword().equals(member.getPassword())){
                return memberDb;
            }else{
                throw  new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }
    /**
     * 获取单个用户
     * @return
     */
    public Member getMemberByMobile(String mobile){
        return memberMapper.findMemberByMobile(mobile);
    }

}
